<?php
/**
 * Content - Simple Product Snapshot
 *
 * @version 1.5.0
 * @package Joomla
 * @subpackage plugins
 * 
 * @author Bruno Pourtier
 * @website http://forge.joomla.org/gf/project/simplesnapshot/
 * @email bruno.pourtier@gmail.com
 * @copyright (C) 2008-2011 Bruno Pourtier
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 *
 * http://www.joomla.org
 *
 * VirtueMart is Free Software.
 * VirtueMart comes with absolute no warranty.
 * http://virtuemart.net
 *
 * Seber Cart is Free Software.
 * Seber Cart comes with absolute no warranty.
 * http://sebercart.com/
 *
 * CLASS FOR SEBER CART
 */
class SeberCartProductSnapshot
{
	var $_regex = '/{sbproduct:.+?}/';
	var $_name	= 'sbproduct';
	var $_pluginPath;
	var $_pluginUrl;
	var $_pluginParams;
	var $_text;
	
	function onPrepareContent()
	{
		// Load SeberCart Configuration file
		include_once(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_sebercart' . DS . 'config.functions.php');
		include_once(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_sebercart' . DS . 'misc.functions.php');

		$CURRENCY_CHAR 		  = getConfigValue("currencySymbol");
		$CURRENCY_THOU_SEP 	= getConfigValue("currencyThousand");
		$CURRENCY_DEC_SEP 	= getConfigValue("currencyDecimalSeparate");
		$CURRENCY_DEC_PLAC 	= getConfigValue("currencyDecimalPlaces");

		// Load VirtueMart Ajax Script & CSS
		$document =& JFactory::getDocument();
		$document->addScript(JURI::root() . 'components/com_sebercart/seberAJAX.js');
		$document->addStyleSheet(JURI::root() . 'components/com_sebercart/custom_style.css');
		
		/**
		 * MAIN VERIFICATION
		 */
		// Check if there is any {sbproduct} or {simpleproduct} in the text
		if ( !preg_match( $this->_regex, $this->_text )) { return false; }
		
		// Check if SeberCart is installed otherwise this plugin doesn't need to be used
		if (!file_exists(JPATH_SITE . DS . 'components' . DS . 'com_sebercart' . DS . 'sebercart.php')) 
		{
			$this->_pluginParams->set('enabled', false);
			if ($this->_pluginParams->get('showerror', 0)) {
				JError::raiseWarning(500, JText::_('SPS_SEBERCART_NOTINSTALLED'));
			}
			return false;
		}
		
		// Check if the plugin is enabled, otherwise replace all {simpleproduct} by blank
		if(!$this->_pluginParams->get('enabled')) 
		{
			$this->_text = preg_replace( $this->_regex, '', $this->_text );
			return true;
		}
		
		/**
		 * PLUGIN PROCESSING
		 */		 
		// Find all instances of plugin and put in $matches
		preg_match_all($this->_regex, $this->_text, $matches);

		// Plugin only processes if there are any instances of the plugin in the text
		if ( count( $matches[0] ) ) 
		{		
			// Get plugin parameters
			foreach ($matches[0] as $match) 
			{
				$match = str_replace("{{$this->_name}:", "", $match);
				$match = str_replace("}", "", $match);
				$this->prepareParams($match);

				$html = "";
				
				// Define SQL request to retrieve product informations from SeberCart database
				$product_id = $this->_pluginParams->get('id', 0, '_product');
				$product_title = $this->_pluginParams->get('title', 0, '_product');
				$where = $product_id ? '`productKey` IN (' . $product_id . ')' : '';
				$where = $product_title ? '`title` LIKE (\'' . $product_title . '\')' : $where;
				
				if ($where) 
				{
					$q = 'SELECT DISTINCT `productKey`, `title`, `briefDescription`, `linkedArticleID`, `stockLevel`';
					$q .= ' FROM `sebercart_products`';
					$q .= ' WHERE ' . $where;
				
					$db =& JFactory::getDBO();
					$db->setQuery($q);
				}
				
				if($db->loadResult()) 
				{					
					// Set the product informations
					$product = $db->loadAssoc();
					$product_id = $product['productKey'];
					if (!$product['linkedArticleID']) { $this->_pluginParams->set('showmore', 0, '_product');  }
					
					$params = array(
						'product_id' 	  => $product_id,
						'product_name' 	=> $product['title'],
						'product_s_desc'=> $product['briefDescription'],
						'product_stock'	=> $product['stockLevel'],
						'product_thumb_image' => htmlentities(JURI::root() . "components/com_sebercart/getPic.php?pk={$product_id}&p=" . JPATH_ROOT),
						// SEF urls						
						'product_link'  => JRoute::_("index.php?option=com_content&view=article&id={$product['linkedArticleID']}", true, -1),
						'addtocart_link'=> JRoute::_("index.php?option=com_sebercart&view=add&pk={$product_id}", true, -1),
						'mycart_link'	  => JRoute::_('index.php?option=com_sebercart&view=cart', true, -1),
						// Not SEF urls
						'product_link_notsef'   => htmlentities(JURI::root() . "index.php?option=com_content&view=article&id={$product['linkedArticleID']}"),
						'addtocart_link_notsef' => htmlentities(JURI::root() . "index.php?option=com_sebercart&view=add&pk={$product_id}"),
						'mycart_link_notsef'    => htmlentities(JURI::root() . 'index.php?option=com_sebercart&view=cart'),
						// Display options
						'show_product_name' 	=> $this->_pluginParams->get('showname',		  $this->_pluginParams->get('showname'), 		  '_product'),
						'show_product_price'	=> $this->_pluginParams->get('showprice', 		$this->_pluginParams->get('showprice'),		  '_product'),
						'show_product_desc' 	=> $this->_pluginParams->get('showdesc', 		  $this->_pluginParams->get('showdesc'), 		  '_product'),
						'show_product_image'	=> $this->_pluginParams->get('showimage', 		$this->_pluginParams->get('showimage'), 	  '_product'),
						'show_product_stock'	=> $this->_pluginParams->get('showstock', 		$this->_pluginParams->get('showstock'), 	  '_product'),
						'show_link_addtocart'	=> $this->_pluginParams->get('showaddtocart',	$this->_pluginParams->get('showaddtocart'),	'_product'),
						'show_link_mycart' 	  => $this->_pluginParams->get('showmycart', 	  $this->_pluginParams->get('showmycart'), 	  '_product'),
						'show_link_readmore'	=> $this->_pluginParams->get('showmore', 		  $this->_pluginParams->get('showmore'), 		  '_product')
					);
					
					// Set the correct template for rendering the product
					if($file = $this->_pluginParams->get('file', $this->_pluginParams->get('file'), '_product')) 
					{
						// Load template file						
						if (file_exists($this->_pluginPath . 'sebercart' . DS . "{$file}.css")) 
						{
							$document->addStyleSheet($this->_pluginUrl . "sebercart/{$file}.css");
						} 
						else
						{
							if ($this->_pluginParams->get('showerror', 0)) {
								JError::raiseWarning(500, sprintf(JText::_('SPS_TEMPLATE_NOFILE'), "{$file}.css"));
							}
						}
						
						if (file_exists($this->_pluginPath .  'sebercart' . DS . "{$file}.tpl.php" )) 
						{
							$html .= include($this->_pluginPath . 'sebercart' . DS . "{$file}.tpl.php" );
						} 
						else 
						{
							if ($this->_pluginParams->get('showerror', 0)) {
								JError::raiseWarning(500, sprintf(JText::_('SPS_TEMPLATE_NOFILE'), "{$file}.tpl.php"));
							}
						}
					}
					else 
					{
						if ($this->_pluginParams->get('showerror', 0)) {
							JError::raiseWarning(500, JText::_('SPS_TEMPLATE_EMPTY'));
						}
					}
				} 
				else 
				{
					if ($this->_pluginParams->get('showerror', 0)) {
						JError::raiseWarning(500, sprintf(JText::_('SPS_PRODUCT_UNAVAILABLE'), ($product_title ? $product_title : $product_id)));
					}
				}

				$this->_text = urldecode(preg_replace( $this->_regex, urlencode($html), $this->_text, 1 ));
			}
		}
	}
	
	function prepareParams($match)
	{
		$this->_pluginParams->bind(array(
			'id' 			      => '',
			'title'			    => '',
			'enabled'		    => $this->_pluginParams->get('enabled', 		  1),
			'forcessl' 		  => $this->_pluginParams->get('forcessl', 		  0),
			'template' 		  => 0,
			'file'			    => $this->_pluginParams->get('file', 			    'default'),
			'showname'		  => $this->_pluginParams->get('showname', 		  1),
			'showdesc'		  => $this->_pluginParams->get('showdesc', 		  1),
			'showimage'		  => $this->_pluginParams->get('showimage', 		1),
			'showprice'		  => $this->_pluginParams->get('showprice', 		1),
			'showstock'		  => $this->_pluginParams->get('showstock', 		1),
			'showquantity'	=> $this->_pluginParams->get('showquantity', 	1),
			'showaddtocart'	=> $this->_pluginParams->get('showaddtocart', 1),
			'showmore'		  => $this->_pluginParams->get('showmore', 		  1),
			'showmycart'	  => $this->_pluginParams->get('showmycart', 	  1)
		), '_product');
		
		$params = explode( ",", $match );
		foreach( $params as $param ) 
		{
			$param = explode( "=", $param );
			$this->_pluginParams->set($param[0], $param[1], '_product');
		}
	}
}
?>